<template>
  <view class="container">
    <div class="content" ref="contentRef" @keydown.space.prevent="handelKeyDown" tabindex="1">
      <view class="textShadow">
        <view class="showText">
          <view class="verticalLine"></view>
          <view class="crosswise"></view>
          <view class="text">
                    {{ showText }}
<!--            头-->
          </view>
          <view class="number"><span>{{ luZhiNum + 1 }}</span><span>/</span><span>{{ allListNumber }}</span></view>
          <view class="textTip" v-if="textTipFlag">看到词语请说出你所联想到的词语</view>
        </view>
      </view>
    </div>
    <view class="errorTip" v-if="passTimeFlag">
      <view class="errorIcon">
        <image src="/static/image/error_icon_red.png"></image>
      </view>
      <span>系统检测到您答题反应时间过长，请开始下一个词的练习</span>
    </view>
    <view class="errorToast" v-if="errorFlag">
      <view class="errorBox">
        <view class="errorIcon">
          <image src="/static/image/error_icon_blue.png"></image>
        </view>
        <view class="errorText">
          您的练习过程中有误
          请返回重新学习操作
        </view>
        <view class="errorBtn">
          重新开始练习
        </view>
      </view>
    </view>
  </view>


</template>

<script setup>
import {
  ref,
  onMounted,
  nextTick
} from 'vue'
import {getAssociationList, setAssociationAnswer} from "@/api/association";
import {onLoad, onReady} from "@dcloudio/uni-app";
import {useRoute} from "vue-router";
const route = useRoute()
const errorFlag = ref(false) //错误提示
const passTimeFlag = ref(false) //超时提示
const token = ref('')  //百度语音token
const resContent = ref('') //百度识别结果
const baiDuKey = {
  appid: "31101339",
  key: "bQzVxn3lvQxotG0bbR2mvo2G",
  secret: "p14P6mxIaVGGLmcAjqVVYjkPddql2nZa",
}

const allListNumber = ref() //总单词数量
const answerState = ref(false) //回答状态，判断是否答题结束
const startTime = ref() //开始时间
const endTime = ref('')
const timeLong = ref() //记录时长
const textTipFlag = ref(false) //文字提示开关（测试）
const optionsList = ref([{
  word: '头',
  index: 1
},
  {
    word: '年报',
    index: 2
  },
  {
    word: '数据',
    index: 3
  },
  {
    word: '女生',
    index: 4
  },
  {
    word: '男人',
    index: 5
  }
]) //题目列表
const luZhiNum = ref(0) //录制序号
const showText = ref('') //显示文字
let curWebview;
const contentRef = ref(null) // 页面实例
const bd = uni.requireNativePlugin("amwhyh-BdspeechByCd");

// #ifdef APP-PLUS
onLoad((query) => {
  if(query.type === "test"){
    textTipFlag.value = true
  }
})
// #endif
// #ifdef H5
onMounted(()=>{
  if(route.query.type === "test"){
    textTipFlag.value = true
  }
})
// #endif
onMounted(async () => {
  await getList()
  if (contentRef.value) {
    console.log(contentRef.value)
  }
  // #ifdef APP-PLUS
  plus.screen.lockOrientation('landscape-primary');
  plus.key.addEventListener('keydown', handelNextText)
  // #endif
  token.value = uni.getStorageSync('baiduToken')
})
const handelKeyDown = () => {
  console.log(111)
}
const handelNextText = (event) => {
  console.log(event)
  if (event.keyCode === 62) {
    nextClick()
  }
}
const getList = () => {
  luZhiNum.value = 0;
  showText.value = optionsList.value[luZhiNum.value].word
  allListNumber.value = optionsList.value.length
  setTimeout(async () => {
    // 开启语音唤醒
    await startWeakUp();
    startYuYinShiBie()
  }, 0)
  // getAssociationList().then(res => {
  //   console.log(res)
  //   if (res.msg === 'success') {
  //     optionsList.value = res.rows
  //     luZhiNum.value = 0;
  //     showText.value = optionsList.value[luZhiNum.value].word
  //     setTimeout(()=>{
  //       startYuYinShiBie()
  //     },0)
  //   }
  // })
}



async function initializeWebView() {
  await nextTick();
  curWebview = uni.getEnv() === 'APP-PLUS' ? uni.getWebviewById(plus.webview.currentWebview().__webviewId__) :
      null;
  if (curWebview) {
    curWebview.setStyle({
      height: "100%",
      scalable: true,
    });
  }
}

const startTimer = () => {
  startTime.value = new Date().getTime()
}
const stopTimer = () => {
  const endTime = new Date().getTime()
  const time = endTime - startTime.value
  timeLong.value = time
}
//文字改变，时间记录开始，语音识别开始
const startYuYinShiBie = () => {
  console.log('开始接收语音信息')
  showText.value = optionsList.value[luZhiNum.value].word //显示第一个词语
  startTimer()
  startShibie()
}
/** 开启语音唤醒 */
const startWeakUp = () => {
  console.log('开启语音接口了')
  console.log(bd)
  //初使化
  bd.init(baiDuKey, function (e) {
    console.log(e);
  });
  //唤醒 参数参照百度文档
  bd.wakeup({}, function (e) {
    if (e.code == 200) {
      console.log("等待唤醒");
    }
    if (e.code == 209) {
      console.log("唤醒成功！唤醒词" + e.words);
      // that.curWebview.evalJS(`getWebviewData(${JSON.stringify(obj)})`)
    }
  });
}
/**下一题*/
const nextClick = async () => {
  if (!answerState.value) {
    stopTimer()
  } else {
    //答题结束，进行下一个模块的逻辑操作
    console.log('答题结束')
  }
}
/**语音识别开始，生成文字上传文字*/
const startShibie = () => {
  bd.startRecognize(baiDuKey, function (res) {
    //一句话最终结果
    if (res.code == 201) {
      console.log("一句话最终结果", res.words, '时长', timeLong.value);
      resContent.value = res.words //获取到识别的文字
      bd.stopRecognize({
        // stop: "",
      })

      luZhiNum.value += 1
      if (luZhiNum.value <= optionsList.value.length - 1) {
        startYuYinShiBie()
      } else {
        console.log('测试结束，即将跳转到下一个模块的逻辑操作')
        answerState.value = true
      }
    }
    //字识别结果
    if (res.code == 200) {
      // console.log("字识别结果", res.words)
    }
    // "accept-audio-volume":true 开启后有语音音量数据回调   【volume】当前音量【volumePercent】当前音量的相对值（0-100）
    if (res.code == 202) {
      // console.log(res.volumePercent);
      // console.log(res.volume);
    }
  });
}
const postAnswer = () => {

  setAssociationAnswer({answer: '脑袋', rid: 1, time: 1920, word: '头'})
}
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
}

.errorToast {
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.8);
  position: fixed;
  left: 0;
  top: 0;

  .errorBox {
    width: 228.93rpx;
    height: 184.08rpx;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    background-image: url("@/static/image/error_icon.png");
    background-size: 100% 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    -webkit-backdrop-filter: blur(10px);
    backdrop-filter: blur(10px);
    padding-top: 32rpx;

    .errorIcon {
      width: 29.25rpx;
      height: 28.08rpx;

      image {
        width: 100%;
        height: 100%;
      }
    }

    .errorText {
      margin-top: 12rpx;
      width: 105.3rpx;
      font-weight: 600;
      font-size: 11.7rpx;
      color: #2FEDFF;
      letter-spacing: 0;
      text-align: center;
    }

    .errorBtn {
      width: 124.8rpx;
      height: 37.05rpx;
      background-image: url("@/static/image/blue_btn.png");
      background-size: 100% 100%;
      font-size: 9rpx;
      letter-spacing: 2rpx;
      line-height: 37.05rpx;
      color: #FFFFFF;
      text-align: center;
      margin-top: 12rpx;
    }
  }
}

.errorTip {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  box-sizing: border-box;
  width: 279.24rpx;
  height: 37.05rpx;
  background: rgba(0, 0, 0, 0.8);
  border-radius: 3.9rpx;
  padding: 11rpx 20rpx;
  display: flex;
  font-weight: 400;
  font-size: 8.58rpx;
  color: #FFFFFF;
  letter-spacing: 0;
  gap: 10rpx;
  align-items: center;

  .errorIcon {
    width: 13.65rpx;
    height: 13.26rpx;

    image {
      width: 100%;
      height: 100%;
    }
  }
}

.content {
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  padding: 43.75rpx;
  position: relative;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-image: url("@/static/image/answer_bg.png");

  .textShadow {
    width: 357.24rpx;
    height: 291.72rpx;
    background: #3B3751;
    box-shadow: 0 0.78rpx 11.7rpx 0 #0000000d;
    border-radius: 7.8rpx;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }

  .showText {
    width: 323.7rpx;
    height: 323.7rpx;
    background: #48445D;
    box-shadow: 0 0.78rpx 11.7rpx 0 #0000000d;
    border-radius: 7.8rpx;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);

    .verticalLine {
      height: 100%;
      width: 1rpx;
      border-right: 1rpx dashed #666;
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
    }

    .crosswise {
      height: 1rpx;
      width: 100%;
      border-bottom: 1rpx dashed #666;
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
    }

    .text {
      position: absolute;
      width: 100%;
      height: 100%;
      z-index: 2;
      font-weight: 400;
      font-size: 78rpx;
      color: #FFFFFF;
      letter-spacing: 0;
      text-align: center;
      line-height: 323rpx;
    }

    .number {
      position: absolute;
      left: 12rpx;
      top: 10rpx;
      font-size: 9.36rpx;
      color: #999;
    }

    .textTip {
      position: absolute;
      left: 50%;
      top: 10rpx;
      transform: translateX(-50%);
      font-size: 9.36rpx;
      color: #999;
    }
  }
}

.logo {
  height: 200rpx;
  width: 200rpx;
  margin-top: 200rpx;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 50rpx;
}

.text-area {
  display: flex;
  justify-content: center;
  margin-top: 10vh;
}

.text-area.recordingStyle {
  width: 39.06rpx;
  height: 39.06rpx;
  border-radius: 50%;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 6.25rpx;
  color: #fff;
  background: #409eff;
}

.Sound_btn {
  display: flex;
  align-items: center;
  margin: 3.91rpx 0 0 0;
}

.Sound_btn > button {
  background: none;
}

.title {
  font-size: 36rpx;
  color: #8f8f94;
}

.reslut_box {
  width: 90%;
  background: #409eff10;
  margin: 1em 5%;
  padding: 0.5em 0;
  border-radius: 10px;
}

.reslut_box p {
  margin: 0 7.81rpx;
}
</style>
